﻿using System;
using System.Data;
using Model;
using Resources;
using Service;

public partial class worOrderRequestIntranet : System.Web.UI.Page
{

    WorkOrderService _WorkOrderService = new WorkOrderService();
    WODirectService _WODirectService = new WODirectService();
    Utility _Utility = new Utility();
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            lblCodeNumber.Text = Resource.LabelWorkOrderAdd;
            if (Request.QueryString["codeNumber"] != null)
            txtEquipCodeNumber.Text = Request.QueryString["codeNumber"];
            //SetDisplayModeToComponents();
        }
    }

    private void SetDisplayModeToComponents()
    {
        bool flagEnable = !String.IsNullOrEmpty(Request.QueryString["displayMode"])
                              ? Request.QueryString["displayMode"].Equals("true") ? false : true
                              :
                                  false;
        btnValidate.Visible = flagEnable;

    }
    private void ClearWorkOrder()
    {
        txtRequiredDate.Text = string.Empty;
        txtNewProblem.Text = string.Empty;
        txtEquipCodeNumber.Text = string.Empty;
        drlCriteria.SelectedIndex = -1;
        drlProblem.SelectedIndex = -1;
    }
    protected void btnValidate_Click(object sender, EventArgs e)
    {
        if (!new Utility().TestPermissions(Resource.PermissionWorkOrderRequest))
        {
            lblInformation.Text = Resource.Permission;
            return;
        }
        lblInformation.Text = string.Empty;
        try
        {

            if (!ValidateData()) return;

            //insert into  workorder 
            WorkOrder workOrder = GetWorkOrder();
            _WorkOrderService.SaveWorkOrder(workOrder);


            //add new problem if not exist
            Problem problem = new Problem();
            if (!String.IsNullOrEmpty(txtNewProblem.Text))
            {

                int groupProbId = new Utility().ConvertToInteger(drlProblem.SelectedValue);

                problem = _WorkOrderService.IsAlreadyExistProblem(groupProbId, txtNewProblem.Text);
                if (problem.ProblemId == 0)
                {
                    problem.GroupProblemId = groupProbId;
                    problem.ProblemLabel = txtNewProblem.Text;
                    _WorkOrderService.SaveProblem(problem);
                }
            }

            // add  taskInworkorder
            WorkOrderTask workOrderTask = GetWorkOrderTask(workOrder.WorkorderId, problem.ProblemId, problem.ProblemLabel);
            _WorkOrderService.SaveWorkOrderTask(workOrderTask);


            //send mail

            ////WODirectService sendmailConfirm = new WODirectService();
            ////int userlocation = Convert.ToInt32(Request.ServerVariables["REMOTE_ADDR"].Substring(7, 2));
            ////string itaddress = "";

            ////if (userlocation == 28 || userlocation == 29)
            ////{
            ////    itaddress = "pnh.it.support@cambodia-airports.aero";
            ////}
            ////else if (userlocation == 30)
            ////{
            ////    itaddress = "rep.it.support@cambodia-airports.aero";
            ////}
            ////else if (userlocation == 31)
            ////{
            ////    itaddress = "kos.it.support@cambodia-airports.aero";
            ////}


            ////sendmailConfirm.sendConfirmWorkorder(workOrder.WorkorderId, txtEquipCodeNumber.Text, problem.ProblemLabel, "chantha.kd@gmail.com");
          //  lblInformation.Text = Resource.WorkOrderRequestConfirm;
            lblPermission.Text = Resource.MessageValidate; 

        }

        catch (Exception ex)
        {

            lblInformation.Text   = ex.Message;
            throw ex;
        }
    }

    private bool ValidateData()
    {
        if (drlCriteria.SelectedIndex == 0)
        {
            lblRequiredCriteria.Text = Resource.MessInformSelectAValue;
            return false;
        }
        lblRequiredCriteria.Text = string.Empty;

        

        lblRequiredDepartment.Text = string.Empty;

        if (String.IsNullOrEmpty(txtRequiredDate.Text))
        {
            lblRequiredRequestDate.Text = Resource.MsgFillInformation;
            return false;
        }
        lblRequiredRequestDate.Text = string.Empty;
        return true;
    }


    private WorkOrder GetWorkOrder()
    {
        WorkOrder workOrder = new WorkOrder();
        workOrder.CriteriaId = Int32.Parse(drlCriteria.SelectedValue);
        workOrder.RequestMadeById = new ReferenceDataService().GetIntranetWORequestTypeId();
        workOrder.EmployeeId = Employee.USERID;
        workOrder.Authorized = false;
        workOrder.RequestDate = DateTime.Parse(DateTime.Now.ToString(Resource.DateEnglishFormat));
        string requestTime = DateTime.Now.Hour + " : " + DateTime.Now.Minute;
        workOrder.RequestTime = DateTime.Parse(requestTime);
        workOrder.AgreedDate = DateTime.Parse(Resource.EmptylDateTime);
        workOrder.RequesterId = Employee.USERID;
        workOrder.StatusId = Int32.Parse(Resource.WorkOrderDefaultStatus);

        return workOrder;

    }
    private WorkOrderTask GetWorkOrderTask(int workOrderId, int problemId, string problem)
    {
        WorkOrderTask workOrderTask = new WorkOrderTask();
        workOrderTask.RequiredDate = new Utility().ConvertToCustomizedFormat(txtRequiredDate.Text);
        workOrderTask.EquipmentCodeNumber = txtEquipCodeNumber.Text;
        workOrderTask.ProblemId = problemId;
        workOrderTask.WorkOrderId = workOrderId;
        workOrderTask.IsCancel = false;
        workOrderTask.ProposedProblem = problem;
        return workOrderTask;

    }
    protected void txtWorkOrderNumber_TextChanged(object sender, EventArgs e)
    {
        DataTable rowFound = _WODirectService.IsCodeNumberExist(txtEquipCodeNumber.Text);
        if (rowFound.Rows.Count == 0)
        {
            lblInformation.Text = Resource.MsgEquipmentCodeInCorrect;
            return;
        }
        lblInformation.Text = string.Empty;
        txtHiddenEquipmentType.Text = rowFound.Rows[0]["typeEquipementID"].ToString();

        drlProblem.DataSource = new ReferenceDataDirectService().GetProblemByTypeEquipmentId(Int32.Parse(txtHiddenEquipmentType.Text));
        drlProblem.DataValueField = "GROUPEPROBLEMID";
        drlProblem.DataTextField = "GROUPEPROBLEM";
        drlProblem.DataBind();

    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        ClearWorkOrder();
    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        Response.Redirect("./Default.aspx");
    }
}
